package com.biqee.model;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.biqee.constant.TBConstant;
import com.biqee.exception.UnexpectedFailureException;
import com.biqee.model.common.PageInfoObject;
import com.biqee.model.db.BqQuery;
import com.biqee.util.StringUtil;

public class TbQueryModel   {
	
	
	public static String QUERY_URL_PRIFIX ="http://s.taobao.com/search?"; 
	
	public static String SORT_BY_SELL_NUM = "biz30day";
	
	public static String SORT_BY_DEFAULT = "coefp";
	
	public static String STYLE_DEFAULT = "list" ;


	
	private String sort = SORT_BY_SELL_NUM;
	
	private String style = STYLE_DEFAULT;
	
	private PageInfoObject pageInfoObject = new PageInfoObject();
	
	private BqQuery bqQuery = new BqQuery();



	public PageInfoObject getPageInfoObject() {
		return pageInfoObject;
	}

	public void setPageInfoObject(PageInfoObject pageInfoObject) {
		this.pageInfoObject = pageInfoObject;
	}


	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}
	

	public String buildQueryUrl(){
		StringBuffer sb = new StringBuffer();
		sb.append(QUERY_URL_PRIFIX);
		if(this.bqQuery.getQueryQ()!=null){
			try {
				sb.append("q="+URLEncoder.encode(this.bqQuery.getQueryQ(), TBConstant.TB_DEFALT_CHARTSET));
			} catch (UnsupportedEncodingException e) {
			  throw new UnexpectedFailureException(e);
			}
		}
		
		if(style!=null){
			sb.append("&style="+style );
		}
		if(sort!=null){
			sb.append("&sort="+style );
		}
		
		if(pageInfoObject!=null){
			sb.append("&s="+pageInfoObject.getStart()+"&n="+pageInfoObject.getLimit() );
		}
		if(bqQuery!=null&&StringUtil.isNotBlank(bqQuery.getQueryParams())){
			sb.append(bqQuery.getQueryParams());
		}
		return sb.toString();
	}
	
	
	public String buildFileName(){
		String indexName = this.bqQuery.getQueryQ()+"_"+this.bqQuery.getQueryParams();
		indexName = Math.abs(indexName.hashCode())+"";
		return TBConstant.HTML_PRIFIX_4_LIST+indexName+"_"+pageInfoObject.getCurrentPageNo()+".html"; 
	}

	public BqQuery getBqQuery() {
		return bqQuery;
	}

	public void setBqQuery(BqQuery bqQuery) {
		this.bqQuery = bqQuery;
	}
	
}
